/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.malva.dbpop.utils;

import java.security.SecureRandom;

/**
 *
 * @author vramirez
 */
public class LongRandom extends SecureRandom {

    public long nextLong(long n) {
        long val;
        if (n <= 0) {
            throw new IllegalArgumentException("n must be positive");
        }

        if ((n & -n) == n) { // i.e., n is a power of 2
            val = ((n * (long) next(31)) >> 31);
            if (val < 0) {
                val *= -1;
            }
            return val;
        }

        long bits;
        do {
            bits = next(31);
            val = bits % n;
        } while (bits - val + (n - 1) < 0);
        if (val < 0) {
            val *= -1;
        }
        return val;
    }
}
